<template>
  <view>
    <u-navbar auto-back title="书籍详情" placeholder safeAreaInsetTop/>
  </view>
  <template v-if="!bookDetail">
    <u-skeleton class="w-full" :loading="true" rows="10" :animate="true"/>
  </template>
  <template v-else>
    <u-swiper
        class="mt-10px"
        :list="compSwiperList"
        :autoplay="false"
        height="260px"
        previousMargin="30"
        nextMargin="30"/>
    <view class="bg-white p-10px rounded-4px shadow m-10px">
      <view class="flex justify-between">
        <view>
          <label class="text-18px font-bold inline-block align-middle mr-10rpx">
            {{ bookDetail.name }}
          </label>
          <view class="text-20rpx p-6rpx rounded-2px inline-block align-middle" :class="bookDetail.status === 0 ? 'state__pend-sale' : bookDetail.status === 1 ? 'state__sold-out' : bookDetail.status === 2 ? 'state__sale' : ''">
            {{ bookDetail.status === 0 ? '销售中' : bookDetail.status === 1 ? '已下架' : bookDetail.status === 2 ? '已售出' : '' }}
          </view>
        </view>
        <u-image mode="shape" :src="bookDetail.user.headUrl" width="30px" height="30px" shape="circle"/>
      </view>
      <view class="mt-10px">
        <template v-for="item in bookDetail.typeList">
<!--          <u-tag :text="item.name"/>-->
          <text class="px-4px py-2px bg-zinc-300 rounded-2px text-10px mr-8px">{{ item.name }}</text>
        </template>
      </view>
      <label class="block inline-normal mt-10px">
        发布时间：{{ dateFormat(bookDetail.createTime, 'datetime') }}
      </label>
      <view class="mt-10px flex justify-between items-end">
        <view>
          <template v-if="bookDetail.oldPrice">
            <label class="line-through text-12px text-slate-400 mr-10px">
              新书：{{ bookDetail.oldPrice }}元
            </label>
          </template>
          <view>
            <label>本书售价：</label>
            <label class="text-18px text-red-500">
              {{ bookDetail.price }}元
            </label>
          </view>
        </view>
        <view>
          <u-icon class="inline-block" name="eye"/>
          {{ bookDetail.viewCount }}
        </view>
      </view>
    </view>
    <view class="bg-white p-10px rounded-4px shadow m-10px">
      <label class="text-16px font-bold mb-10px block">
        简介
      </label>
      <view>
        {{ bookDetail.intro }}
      </view>
    </view>
    <view class="bg-white p-10px rounded-4px shadow m-10px">
      <label class="text-16px font-bold mb-10px block">
        实物图片
      </label>
      <template v-for="item in compNewImgs">
        <u-image :src="item" width="100%" mode="widthFix"/>
      </template>
    </view>
    <view class="fixed left-0 right-0 bottom-0 bg-white p-10px flex justify-between">
      <view></view>
      <view>
        <template v-if="user.userInfo?.uId !== bookDetail?.user?.uId && bookDetail?.status !== 2">
          <button class="inline-block mr-10px" size="mini" @click="handlerRelation">联系卖家</button>
        </template>
        <template v-else-if="bookDetail?.status !== 0 && bookDetail?.status !== 1">
          <template v-if="bookDetail?.status === 0">
            <button class="inline-block mr-10px" size="mini" @click="handlerSale">售出</button>
            <button class="inline-block mr-10px" size="mini" @click="handlerSoldOut">下架</button>
          </template>
          <template v-if="bookDetail?.status === 1">
            <button class="inline-block mr-10px" size="mini" @click="handlerRack">重新上架</button>
          </template>
        </template>
<!--        <button class="inline-block w-150px" type="warn" size="mini">购买</button>-->
      </view>
    </view>
  </template>
  <u-toast ref="uToast"/>
</template>

<script setup lang="ts">
import type {Book } from "@/api/book";
import UNavbar from "@/uni_modules/uview-plus/components/u-navbar/u-navbar.vue";
import {ref, computed} from "vue";
import USwiper from "@/uni_modules/uview-plus/components/u-swiper/u-swiper.vue";
import UToast from "@/uni_modules/uview-plus/components/u-toast/u-toast.vue";
import userStore from '@/store/user'
import UIcon from "@/uni_modules/uview-plus/components/u-icon/u-icon.vue";
import UImage from "@/uni_modules/uview-plus/components/u-image/u-image.vue";
import {getBookById, putSetStatus, putView} from "@/api/book";
import {onLoad} from "@dcloudio/uni-app";
import USkeleton from "@/uni_modules/uview-plus/components/u-skeleton/u-skeleton.vue";
import {dateFormat} from "@/utils";
import store from "@/pages/TUIKit/TUICore/store";

const TUIConversationServer = uni.$TUIKit.TUIConversationServer

const uToast = ref<UToast>(null)
const user = userStore()
// 书籍详情信息
const bookDetail = ref<Book | null>(null)
const compSwiperList = computed(() => {
  const imageList = bookDetail.value ? [
    bookDetail.value.cover
  ] : []
  const detailImgs = bookDetail.value ? bookDetail.value.imgs.split(',') : []
  if (detailImgs.length > 0)
    imageList.push(...detailImgs)
  return imageList
})
const compNewImgs = computed(() => {
  return bookDetail.value ? bookDetail.value.imgs.split(',') : []
})
const fnGetBookById = async (bid: number) => {
  const data = await getBookById(bid)
  await fnPutView(bid, data.data.user.uId)
  bookDetail.value = data.data
}
const fnPutView = async (bid: number, uid: string) => {
  console.log('user', user.userInfo, uid)
  if(user.userInfo?.uId && uid !== user.userInfo?.uId){
     await putView(bid)
  }
}
onLoad((option) => {
  if(option?.bid){
    fnGetBookById(option.bid)
  }else{
    uToast.value && uToast.value.show({
      type: 'error',
      message: '未获取到书籍ID'
    })
  }
})
const fnPutSetStatus = async (bid: number, status: 0 | 1 | 2) => {
  await putSetStatus(bid, status)
  await fnGetBookById(bid)
}
// 售出
const handlerSale = () => {
  bookDetail.value && fnPutSetStatus(bookDetail.value.bid, 2)
}
// 下架
const handlerSoldOut = () => {
  bookDetail.value && fnPutSetStatus(bookDetail.value.bid, 1)
}
// 重新上架
const handlerRack = () => {
  bookDetail.value && fnPutSetStatus(bookDetail.value.bid, 0)
}
// 切换当前会话
const handleCurrrentConversation = (conversationID: string) => {
  store.commit("timStore/setConversationID", conversationID);
  console.log('uni', uni.$TUIKit)
  uni.$TUIKit.TUIConversationServer.setMessageRead(conversationID);
  TUIConversationServer.getConversationProfile(conversationID)
    .then((res) => {
      // 通知 TUIChat 关闭当前会话
      const { conversation } = res.data;
      store.commit("timStore/setConversation", conversation);
      uni.$TUIKit.TUIConversationServer.getConversationProfile(
        conversationID
      ).then((res: any) => {
        // 通知 TUIChat 关闭当前会话
        store.commit("timStore/setConversation", res.data.conversation);
        // uni.$TUIKit.getStore()['TUIChat'].conversation = res.data.conversation;
      });
    })
    .catch((err) => {
      console.warn("获取 group profile 异常 = ", err);
    });
  //uni.$TUIKit.TUIChatServer.updateStore(value.conversationID)
  uni.navigateTo({
    url: `/pages/TUIKit/TUIPages/TUIChat/index?conversationName=${bookDetail.value?.user?.name || bookDetail.value?.user?.uId || ""}`,
  });
};
// 联系卖家按钮点击事件
const handlerRelation = () => {
  bookDetail.value?.user?.uId && handleCurrrentConversation("C2C" + bookDetail.value?.user?.uId)
}
</script>

<style lang="scss">
.state{
    &__pend-sale{
        background-color: #f0ad4e;
        color: #fff;
    }
    &__sale{
        background-color: #4cd964;
        color: #fff;
    }
    &__sold-out{
        background-color: #8F959E;
        color: #fff;
    }
}
</style>
